//
// Created by edward on 23-5-23.
//
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#include <stdio.h>
#include <sys/stat.h>
#include <fcntl.h>
#include "terminal.h"


int main(int argc, char *argv[]) {

    const char *path = "./proconnect";
    const char *configPath = "../config/config.txt";
    const char *logLevel = "INFO";
    const char *pTerminalNum = "36";
    int terminalNum = atoi(pTerminalNum);
    char buf[BUFSIZ];

    /*
    int fd = open("../log/log.txt", O_WRONLY | O_CREAT | O_TRUNC, S_IRUSR | S_IWUSR);
    if (fd == -1) {
        // 处理错误
        return 1;
    }

    if (dup2(fd, STDERR_FILENO) == -1) {
        // 处理错误
        return 1;
    }
     */


    //创建36个终端进程，并传入不同的终端编号
    pid_t pids[MAX_TERMINAL_NUM], pid;
    for (int i = 0; i < terminalNum; ++i) {
        pid = fork();
        if (pid < 0) {
            //error
            perror("fork error\n");
        } else if (pid > 0) {
            //parent
            pids[i] = pid;
//            sleep(1);
//            printf("terminal %d is created\n", i);
        } else {
            //child
            snprintf(buf, BUFSIZ, "%d", i);
            execl(path, path, buf, "--config", configPath, "--log-level", logLevel, "--terminal-num", pTerminalNum, NULL); //传入终端编号
            //正常情况下应该不会返回
            perror("exec error\n");
            return 1;
        }
    }
    for (int i = 0; i < terminalNum; ++i) {
        wait(NULL);
    }

    return 0;
}